import router from '@/routers/index'
import type { RouteRecordRaw } from 'vue-router'
import useAuthStore from '@/stores/modules/auth.ts'
import type { SidebarMenu } from '@/types/router'
import { hasPermission } from '@/utils/permission'

const filterRoutesByPermission = (
  routes: RouteRecordRaw[],
  permissionList: string[],
): RouteRecordRaw[] => {
  return routes.filter((route) => {
    // 1. 检查当前路由是否有权限
    const hasAccess = hasPermission(route.meta?.permission, permissionList)
    return hasAccess
  })
}

const formatSidebarMenu = (routes: RouteRecordRaw[]): SidebarMenu[] => {
  const menuMap = new Map<string, SidebarMenu>()
  const menuMetaMap = useAuthStore().getMenuMetaMap

  // 第一步：处理所有路由，生成基础菜单节点
  routes.forEach((route) => {
    const { path, name, meta } = route
    if (!path || !meta) return

    // 创建基础菜单节点
    const menuNode: SidebarMenu = {
      path,
      meta,
    }

    menuMap.set(path, menuNode)
  })

  // 第二步：为所有缺失的中间层级父路由创建节点
  const allPaths = Array.from(menuMap.keys())
  const neededParents = new Set<string>()

  // 收集所有需要的父级路径
  allPaths.forEach((path) => {
    const segments = path.split('/').filter(Boolean)
    for (let i = 1; i < segments.length; i++) {
      const parentPath = '/' + segments.slice(0, i).join('/')
      if (!menuMap.has(parentPath)) {
        neededParents.add(parentPath)
      }
    }
  })

  // 创建缺失的父级路由节点
  neededParents.forEach((parentPath) => {
    const parentMenu: SidebarMenu = {
      path: parentPath,
      meta: menuMetaMap.get(parentPath),
      children: [],
    }
    menuMap.set(parentPath, parentMenu)
  })

  // 第三步：构建完整的父子层级关系
  menuMap.forEach((menuNode) => {
    const pathSegments = menuNode.path.split('/').filter(Boolean)
    if (pathSegments.length <= 1) return

    // 生成直接父路径
    const parentPath = `/${pathSegments.slice(0, -1).join('/')}`
    const parentMenu = menuMap.get(parentPath)

    if (parentMenu) {
      parentMenu.children?.push(menuNode)
    }
  })

  // 第四步：筛选出根菜单（一级菜单）
  return Array.from(menuMap.values()).filter((menu) => {
    const pathSegments = menu.path.split('/').filter(Boolean)
    return pathSegments.length === 1
  })
}

export const initDynamicRouter = async (menuList: RouteRecordRaw[]) => {
  const authStore = useAuthStore()
  const permissionList: string[] = authStore.getPermissionList
  // 根据权限过滤路由
  const accessibleRoutes = filterRoutesByPermission(menuList, permissionList)
  // 直接添加路由，无需延迟
  accessibleRoutes.forEach((item: RouteRecordRaw) => {
    router.addRoute('layout', item)
  })
  // 获取meta.isHide 为false 的路由 和 path 是 / 生成 sidebarRoutes
  const sidebarRoutes = router.getRoutes().filter((item: RouteRecordRaw) => {
    return item.meta?.isHide !== true && item.path !== '/'
  })
  // 构建 菜单树
  const sidebarMenu = formatSidebarMenu(sidebarRoutes)
  authStore.setRecursiveMenuList(sidebarMenu)
}
